package com.readingtree.library.security;

import com.readingtree.library.domain.SecurityUser;
import com.readingtree.library.service.JWTTokenService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginSuccessHandler extends
        SimpleUrlAuthenticationSuccessHandler {

    private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(LoginSuccessHandler.class);

    @Autowired
    private JWTTokenService jwtTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        //获得授权后可得到用户信息   可使用UserService进行数据库操作
        SecurityUser userDetails = (SecurityUser) authentication.getPrincipal();
        LOGGER.info("user" + userDetails.getUsername() + "has logined");
        if (userDetails != null) {
            String token = jwtTokenService.createJWTToken(userDetails);
            response.setHeader("Authorization", token);
        }
    }
}